import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;

public class Solution1284 {
    public int minFlips(int[][] mat) {
        Queue<Integer> queue=new LinkedList<>();
        int n=mat.length,m=mat[0].length;
        int[] f=new int[1<<(m*n)];
        Arrays.fill(f,Integer.MAX_VALUE);
        f[convert(mat)]=0;
        queue.offer(convert(mat));
        while (!queue.isEmpty()){
            int t=queue.poll();
            int[][] p=shift(t,n,m);
            for (int i=0;i<n;i++){
                for (int j=0;j<m;j++){
                    int[][] q=reverse(p,i,j);
                    if (f[convert(q)]>f[t]+1){
                        f[convert(q)]=f[t]+1;
                        queue.offer(convert(q));
                    }
                }
            }
        }
        return f[0]==Integer.MAX_VALUE?-1:f[0];
    }

    private int[][] reverse(int[][] p, int x, int y) {
        int[][] q=new int[p.length][p[0].length];
        for (int i=0;i<p.length;i++){
            System.arraycopy(p[i], 0, q[i], 0, p[0].length);
        }
        int[] dx=new int[]{1,0,-1,0};
        int[] dy=new int[]{0,1,0,-1};
        for (int i=0;i<4;i++){
            int xx=x+dx[i];
            int yy=y+dy[i];
            if (xx>=0 && xx<p.length && yy>=0 && yy<p[0].length){
                q[xx][yy]=1-q[xx][yy];
            }
        }
        q[x][y]=1-q[x][y];
        return q;
    }

    private int[][] shift(int t,int n,int m) {
        int[][] a=new int[n][m];
        for (int i=0;i<n;i++){
            for (int j=0;j<m;j++){
                a[i][j]=(t>>(i*m+j))&1;
            }
        }
        return a;
    }

    private int convert(int[][] mat) {
        int ans=0;
        for (int i=0;i<mat.length;i++){
            for (int j=0;j<mat[0].length;j++){
                ans+=mat[i][j]*(1<<(i*mat[0].length+j));
            }
        }
        return ans;
    }

    public static void main(String[] args) {
        System.out.println(new Solution1284().minFlips(new int[][]{{0,0},{0,1}}));
    }
}
